from urllib2 import urlopen, URLError
import json
import logging
from time import time as now
from google.appengine.api import memcache

class MsgApiBase:

    def __init__(self):
        self.appid = 'wx8fab3933d55bde7a'
        self.appkey = '1c5fc7c871158dc443bc923d0a051467'

    @property
    def access_token(self):
        token = memcache.get('token_' + self.appid)
        if token:
            logging.info('get token(%s) from cache!', token)
            return token

        url = r'https://api.weixin.qq.com/token.json?appid=%s&grant_type=client_credential&secret=%s'%(self.appid, self.appkey)
        try:
            token_json = urlopen(url).read()
        except URLError, e:
            logging.error('urlopen error! msg: %s'%e)
            return None

        logging.info('get tokenjson(%s) from server!', token_json)
        token_dict = json.loads(token_json)
        token = token_dict['access_token']
        memcache.set('token_'+self.appid, token, token_dict['expires_in']/2)
        logging.info('get token(%s) from server!', token)

        return token
